<!-- 此页为翻转180度后 反向的 -->
<template>
	<m-layout :title="touserName" class="chat flex-column" :style="{height:Hights}" gap="0" @click='tapS'
		:showBack="false">
		<view slot="back">
			<m-icon @click="handleBack" size="38" type="icon-fanhui"></m-icon>
		</view>
		<template>
			<m-icon type="icon-shezhi" slot="right" @click="Jump('/pages/chat/setting/setting')"></m-icon>
		</template>
		<view class="main overturn">
			<scroll-view upper-threshold="150" :scroll-top="scrollTop" @scroll="scroll" @scrolltolower="scrolltolower"
				@scrolltoupper="scrolltoupper" class="scroll-view" scroll-y="true">
				<view class="" v-for="(item,idx) in captain" >
					<msgItem class="pb-16" :item.sync="allMes[item]" @longpressIn="onLongPress($event,allMes[item])" />
				</view>
				<!-- <view class="" v-for="(item,idx) in captain" @longpress="onLongPress($event,allMes[item])">
					<msgItem class="pb-16" :item.sync="allMes[item]" />
				</view> -->
				<!-- <template v-for="(item,idx) in captain">
					<msgItem class="pb-16" :item.sync="allMes[item]" />
				</template> -->
				<m-loading class="overturn" :list="captain" title="暂无消息" :loading="isLoading" :pageIndex="pageIndex"
					:pageCount="pageCount">
				</m-loading>
			</scroll-view>
		</view>
		<!-- 商品详情 -->
		<view class="goodsCard" v-if="goodsInfo.goodsname">
			<m-block bgColor="#fff" gap="20 20" spa="30 20" class=" flex">
				<m-image2 :src="goodsInfo.picurl" radius="12" :size="[130,130]" />
				<view class=" flex-1 pl-16 flex-column">
					<view class="flex-between">
						<view class="otw flex-1" style="width: 100rpx;">
							{{goodsInfo.goodsname}}
						</view>
						<m-icon gap="8" type="icon-guanbi1" @click="goodsInfo.goodsname=''" />
					</view>
					<view class="text-grey fs24 mb-8 mt-4">
						<text v-if="goodsInfo.attr&&goodsInfo.attr.goodsname">{{goodsInfo.attr.goodsname}}</text>
						<text v-else>默认规格</text>
					</view>
					<view class="flex-between">
						<view class="flex">
							<m-price  class="flex-1" :value="goodsInfo.price" :size="[36,21]" />
						</view>
						<m-button type="small" bgColor="red" color="#fff" :loading="sendLoading"
							@click="sendGoodsInfo()">发送</m-button>
					</view>
				</view>
			</m-block>
		</view>
		<!-- 底部操作 -->
		<view class="footer ">
			<view class="unread-box" @click="goTop()" v-if="unreads>0">
				<m-icon type="icon-shuangjiantou-xia" rotate="90" size="24" color="#66c18c" spa="0 10 0 0"></m-icon>
				<text></text>
			</view>
			<Actionbar ref="actionbar" @onOper="onOper" :touid="Number(touid)" :IncomingMsg='inMsg' @setIncomingMsg="setIncomingMsg()"></Actionbar>
		</view>
	    <!--
	    	 wxPupData：子组件需要接收的数据
	    	 getNewList：通知父组件，更新数据。
	     -->
	    <wxpup ref="wxpup" :wxPupData="wxPupData" @getNewList="getNewList"  @referenceMsg="referenceMsg($event)"></wxpup>
	</m-layout>
</template>
<script>
	import { getmsgcontent, sendmsg, ReadAll } from "@/api/msg.js"
	import { MallShopInfo } from "@/api/Goods.js"
	import { mapState, mapMutations } from 'vuex'
	import Actionbar from './components/actionbar.vue'
	import msgItem from './components/msgItem.vue'
	import wxpup from './components/wxpup.vue'
	export default {
		components: { Actionbar, msgItem,wxpup },
		data() {
			return {
				listArr: [],
				pageSize: 20,
				pageIndex: 1,
				pageCount: 1,
				isLoading: true,

				isUnread: 0, //未读条数
				scrollTop: 0, //距离顶部
				oldScrollTop: 1, //上一次滑动距离顶部
				//处理IOS端显示窗口问题
				Hights: 0,

				itemHeight: 0, //消息高度
				isOperaiton: false,
				unreads: 0,

				// add
				touid: '',
				goodsInfo: {}, // 商品信息
				shopInfo: {},
				sendLoading: false,
                wxPupData:{},
				inMsg:{}
			}
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
				allMes: state => state.chat.allMes,
				captain: state => state.chat.captain,
				unread: state => state.chat.unread,
			}),
		},
		watch: {
			captain(val) {
				///消息列表改变  更新一下未读
				this.unreadFn();
			},
		},
		async onLoad({ touid, touserName, goodsInfo, type } = {}) {
			this.type = type;
			this.touid = touid; // 客服ID
			this.touserName = touserName; // 客服昵称
			console.log('goodsInfo===>', goodsInfo)
			if (goodsInfo) {
				this.goodsInfo = JSON.parse(goodsInfo)
			}
			if (this.type == 2) {
				// const { success, data } = await MallShopInfo({
				// 	id: this.touid
				// });
				// console.log('data===>', data)
				// if (success) {
				// 	this.shopInfo = data;
				// }
			}
			this.CLEAR_CAPTAIN();
			// 消息已读
			this.ReadAll()
		},
		onShow() {
			this.Ws.reconnect();
		},
		async mounted() {
			this.safariHacks();
			await this.getmsgcontent();
		},
		// 销毁或离开页面  清空所有消息
		beforeDestroy() {
			this.Ws.completeClose();
			this.CLEAR_CAPTAIN();
		},
		onUnload() {
			this.Ws.completeClose();
			this.CLEAR_CAPTAIN();
		},
		methods: {
			...mapMutations({
				CLEAR_CAPTAIN: 'chat/CLEAR_CAPTAIN',
				SET_ALLMES: 'chat/SET_ALLMES',
				HISTORY_MES: 'chat/HISTORY_MES',
				SET_MES: 'chat/SET_MES',
				Add_ONE: 'chat/Add_ONE',
				DELETE_MSG:'chat/DELETE_MSG',
			}),
			setIncomingMsg(e){
				this.inMsg={}
			},
			// 引用msg
			referenceMsg(id){
				console.log('id===>',id);
				let msg=this.allMes[id];
				this.inMsg=msg;
			},
			/* 长按监听 */
			onLongPress(e, item) {
				console.log('e===>',e)
				this.$refs.wxpup.hidePop()
				e.item = item;
				// e.my_user_id = this.my_userInfo.id;
				this.wxPupData = e;
				// console.log(this.wxPupData)
			},
			async handleBack() {
				await this.ReadAll();
				this.Jump()
			},
			// 消息玩不已读
			async ReadAll() {
				const { success, msg } = await ReadAll({
					fromuid: this.touid
				})
			},
			// 发送 商品信息
			async sendGoodsInfo() {
				let dataObj = {};
				const tokenid = Date.parse(new Date()) / 1000
				dataObj = {
					ctime: tokenid,
					type: 3,
					content: this.goodsInfo,
				}
				const msgs = {
					id: tokenid,
					fromheadpic: this.userinfo.headpicurl,
					fromnickname: this.userinfo.nickname,
					fromuid: this.userinfo.userid,
					isLoading: true,
					sencmsgcontent: JSON.stringify(dataObj)
				}
				this.Add_ONE(msgs);
				// this.ADD_LOADING(msgs);
				// await this.sleep(3000);
				this.sendmsg({
					touid: this.touid,
					msgtype: 3,
					msgcontent: JSON.stringify(dataObj).replace(' ', ''),
				})
			},
			/**
			 * types   消息类型
			 * params  content内容
			 * msg     此参数用作本地预发消息的  loading形式消息用
			 * */
			async sendmsg(data) {
				this.sendLoading = true;
				const { success, msg } = await sendmsg(data)
				this.sendLoading = false;
				if (success) {
					this.goodsInfo = {}
				} else {
					this.Toast(msg)
				}
			},
			//IOS 高度
			async safariHacks() {
				// console.log(uni.getSystemInfoSync().windowHeight)
				this.Hights = uni.getSystemInfoSync().windowHeight + 'px';
				console.log('this.Hights+++',this.Hights)
			},
			//全局点击
			tapS() {
				if (this.isOperaiton) {
					setTimeout(() => {
						this.$refs.actionbar.isOperaiton = false;
					}, 1)
				}
			},
			onOper(e) {
				this.isOperaiton = e;
			},
			async goScroll(length = 1000000123) {
				this.scrollTop = this.oldScrollTop;
				await this.sleep(0.01)
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollTop = length
					})
				})
			},
			// 滑动时
			scroll({ detail }) {
				// console.log('detail===>', detail)
				const { scrollHeight, scrollTop } = detail;
				this.oldScrollTop = scrollTop;
			},
			//获取历史消息
			async getmsgcontent() {
				if (this.pageIndex > this.pageCount) {
					return
				}
				this.isLoading = true;
				const { list, pageCount: pageCount } = await getmsgcontent({
					fromuid: this.touid,
					pageSize: this.pageSize,
					pageIndex: this.pageIndex,
				});
				this.isLoading = false;
				this.pageCount = pageCount;
				//处理消息数据
				list.reverse().map(item => {
					this.SET_ALLMES(item);
				})
				this.pageIndex++;
				return Promise.resolve(true)
			},
			//触顶
			async scrolltolower() {
				console.log('触顶了')
				const status = await this.getmsgcontent();
			},
			//回到顶部
			goTop() {
				this.goScroll(0)
			},
			//触底
			async scrolltoupper(e) {
				console.log('触底')
				// 触底计算新消息
				this.SET_MES();
				this.unreadFn();
			},
			unreadFn() {
				/**
				 *  新消息触发时
				 *  滑动大于150(表示在可见范围外)
				 *  小于150 清空未读消息的条数 SET_MES
				 * */
				if (this.oldScrollTop < 80) {
					this.SET_MES();
				} else {
					this.unreads = this.unread.length
					// 处理有新消息时记录页会往上顶
					// this.scrollTop = this.oldScrollTop + this.itemHeight;
				}
			},
		},

	}
</script>

<style lang="scss">
	.noData {
		padding-top: 15rpx;
		text-align: center;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: rgba(153, 153, 153, .8);
	}

	.loading {
		position: absolute;
		top: 0;
		left: 0;
		text-align: center;
		width: 100%;
		padding-top: 25rpx;

		image {
			width: 40rpx;
			height: 40rpx;
			animation: rotate 1s infinite linear;
		}
	}

	.chat {
		height: 100vh !important;
		overflow: hidden;

		::v-deep .layout-content {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			position: relative;
		}

		.main {
			flex: 1;
			overflow: hidden;

			.scroll-view {
				min-height: 70vh;
				height: 100%;
			}

			.m-loadingP {}
		}

		.footer {
			width: 100%;
			left: 0;
			bottom: 0;
			// bottom: env(safe-area-inset-bottom);
			background: #fff;

			.unread-box {
				position: absolute;
				right: 0;
				top: -100rpx;
				color: #E3C01C;
				padding: 15rpx 20rpx;
				background: #333333;
				border-radius: 15rpx 0 0 15rpx;
				font-size: 24rpx;
			}
		}
	}

	.goodsCard {
		box-sizing: border-box;
		bottom: 56px;
		position: absolute;
		z-index: 22;
		width: auto;
		width: 100%;
	}
</style>